package edu.neu.cs6515.xml.converter;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import edu.neu.cs6515.xml.Board;
import edu.neu.cs6515.xml.Placement;
import edu.neu.cs6515.xml.w12.XMLTurn;

public class BoardConverter implements Converter {

    @Override
    public boolean canConvert(final Class type) {
        return Board.class.equals(type);
    }

    @Override
    public void marshal(final Object source,
            final HierarchicalStreamWriter writer,
            final MarshallingContext context) {
        Board board = (Board) source;
        writer.addAttribute("players", String.valueOf(board.getPlayers()));
        for (Placement p : board.getPlacement()) {
            writer.startNode("placement");
            context.convertAnother(p);
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
        int players = Integer.valueOf(reader.getAttribute("players"));
        List<Placement> placements = new ArrayList<Placement>();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            PlacementConverter pc = new PlacementConverter();
            Placement p = (Placement) pc.unmarshal(reader, context);
            placements.add(p);
            reader.moveUp();
        }
        Board board = new Board(placements, players);
        return board;
    }

}